// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function () { // 通用预处理器

	},
	/**
	 * 根据用户id删除用户所有的数据以及用户信息
	 * @param userId:用户id
	 * @returns 删除后的结果 bool
	 */
	
    async delUserByUserid(userId) {
		var db = uniCloud.database();
		var orders = await db.collection('orders').where({user_id:userId}).remove();//删除所有的订单
		var circle = await db.collection('circle').where({user_id:userId}).remove();//删除派小圈
		var circleComment = await db.collection('circle_comment').where({user_id:userId}).remove();//删除派小圈评论
		var usersBill = await db.collection('users_bill').where({user_id:userId}).remove();//删除进出账明细信息
		var usersCollect = await db.collection('users_collect').where({'user._id':userId}).remove();//删除收藏
		var usersOpinion = await db.collection('users_opinion').where({user_id:userId}).remove();//删除意见反馈
		var usersReport = await db.collection('users_report').where({user_id:userId}).remove();//删除投诉举报
		var usersSearchHistory = await db.collection('users_search_history').where({user_id:userId}).remove();//删除搜索记录
		var usersAddress = await db.collection('users_address').where({user_id:userId}).remove();//删除地址
		var uniIdDevice = await db.collection('uni-id-device').where({user_id:userId}).remove();//删除登录设备表信息
		setTimeout(function(){
			return true;
		},3000);
		
	},
	//获取用户数量
	async getUsersCount(){
		var db = uniCloud.database();
		var cmd = db.command;
		var userCountResult = await db.collection('uni-id-users').count();
		var userCount = userCountResult.total;//总用户数
		//查询出今日新增用户
		 const todayStartTimestamp = Math.floor(new Date(new Date().setHours(0, 0, 0, 0)).getTime());//今日开始时间戳
		const todayEndTimestamp = Math.floor(new Date(new Date().setHours(23, 59, 59, 999)).getTime());//今日结束时间戳
		var todayAddUsersCountResult = await db.collection('uni-id-users').where({
			register_date:cmd.gt(todayStartTimestamp).and(cmd.lt(todayEndTimestamp))
		}).count();
		var todayAddUsers = todayAddUsersCountResult.total;//今日新增用户
		//获取本周新增用户
		//  一天的秒数
		  const MillisecondsADay = 24 * 60 * 60 * 1000
		  //  今日零点时间戳
		  const timestamp = Math.floor(new Date(new Date().setHours(0, 0, 0, 0)).getTime())
		  const weekDay = new Date().getDay() === 0 ? (7 - 1) : (new Date().getDay() - 1)
		  const weekTimeStamp = timestamp - MillisecondsADay * weekDay //本周开始时间戳
		
		var weekAddUsersCountResult = await db.collection('uni-id-users').where({
			register_date:cmd.gt(weekTimeStamp)
		}).count();
		var weekAddUsersCount = weekAddUsersCountResult.total;//本周新增用户
		//获取本月新增用户
		const date = new Date()
		  date.setDate(1)
		  date.setHours(0, 0, 0, 0)
		  const monthTimeStamp = date.getTime();//本月开始时间戳
		  var monthAddUsersCountResult = await db.collection('uni-id-users').where({
		  	register_date:cmd.gt(monthTimeStamp)
		  }).count();
		  var monthAddUsersCount = monthAddUsersCountResult.total;//本周新增用户
		return {
			todayNewsAddUsers:todayAddUsers,//今日新增用户
			userCounts:userCount,//用户总数
			weekNewsAddUsersCount:weekAddUsersCount,//本周新增用户
			monthNewsAddUsersCount:monthAddUsersCount//本月新增用户
		}
	},
	//获取订单数据
	async getOrdersCount(){
		var db = uniCloud.database();
		var cmd = db.command;
		//查询总订单数量
		var ordersCountResult = await db.collection('orders').where({
			'pay_date':db.command.neq(null),
			'status.value':cmd.gt(0).and(cmd.neq(9))
		}).count();
		var ordersCount = ordersCountResult.total;//总订单数量
		
		
		var date = new Date();
		var today = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
		//查询今日订单数量
		var todayOrdersCountResult = await db.collection('orders').where({
			'create_date.today':today,
			'pay_date':db.command.neq(null),
			'status.value':cmd.gt(0).and(cmd.lt(9))
		}).count();
		var todayOrdersCount = todayOrdersCountResult.total;//今日订单数量
		//查询昨日订单数量
		var dates = date.getDate();
		if(dates!=1){
			var todayDate = dates - 1;
		}else{
			var curMonth = date.getMonth();
				// 实际月份比curMonth大1，下面将月份设置为下一个月
				date.setMonth(curMonth);
				// 将日期设置为0，表示自动计算为上个月（这里指的是当前月份）的最后一天
				date.setDate(0);
				// 返回当前月份的天数
				var todayDate = date.getDate()
		}
		var yesterday = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+todayDate;
		//查询昨日订单数量
		var yesterdayOrdersCountResult = await db.collection('orders').where({
			'create_date.today':yesterday,
			'pay_date':db.command.neq(null),
			'status.value':cmd.gt(0).and(cmd.lt(9))
		}).count();
		var yesterdayOrdersCount = yesterdayOrdersCountResult.total;//昨日订单数量
		//查询出今日转化率
		var where = {
			'create_date.date':today,
			'user.user_id':db.command.neq(null)
		}
	
		return {
			ordersCount:ordersCount,//总订单量
			todayOrdersCount:todayOrdersCount,//今日订单总数
			yesterdayOrdersCount:yesterdayOrdersCount,//昨日订单数量
			todayRate:'··',//今日转化率
		};
	},
	async getShopCount(){
		var db = uniCloud.database();
		var cmd = db.command;
		//查询出店铺总数
		var shopCountResult = await db.collection('shop').count();
		var shopCount = shopCountResult.total;
		//查询出正常营业的店铺
		var tradeShopCountResult = await db.collection('shop').where({
			disabled_status:true,
			business_status:true
		}).count();
		var tradeShopCount = tradeShopCountResult.total;
		//查询出歇业中的店铺
		var stopShopCountResult = await db.collection('shop').where({
			disabled_status:true,
			business_status:false
		}).count();
		var stopShopCount = stopShopCountResult.total;
		
		//查询出查封的店铺
		var closeShopCountResult = await db.collection('shop').where({
			disabled_status:false,
			business_status:false
		}).count();
		var closeShopCount = closeShopCountResult.total;
		
		//查询出待审核的店铺
		var examineShopCountResult = await db.collection('shop_authentication').where({
			audit_status:false
		}).count();
		var examineShopCount = examineShopCountResult.total;
		
		return {
			shopCount:shopCount,//店铺总数
			tradeShopCount:tradeShopCount,//正常营业店铺总数
			stopShopCount:stopShopCount,//歇业中店铺总数
			closeShopCount:closeShopCount,//查封店铺总数
			examineShopCount:examineShopCount,//待审核店铺数量
			
		};
	},
	
	//平台利润
	async getIncomeCount(){
		var date = new Date();
		var today = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
		var db = uniCloud.database();
		const $ = db.command.aggregate
		//获取平台总收入
		let incomeCount = await db
		  .collection('platform_bill')
		  .aggregate()
		  .group({
		    _id: null,
		    totalPrice: $.sum('$price')
		  })
		  .end()
		  
		  if(incomeCount.affectedDocs==1){
			  var incomeCountPrice = incomeCount.data[0].totalPrice;
		  }else{
			  var incomeCountPrice = 0;
		  }
		  //获取今日收入
		  let todayIncomeCount = await db
		    .collection('platform_bill')
		    .aggregate().match({
				'create_date.today': today
			  })
		    .group({
		      _id: null,
		      totalPrice: $.sum('$price')
		    })
		    .end()
		
			if(todayIncomeCount.affectedDocs==1){
				var todayIncomeCountPrice = todayIncomeCount.data[0].totalPrice;
			}else{
				var todayIncomeCountPrice = 0;
			}
		
			//查询出本周收入
			//  一天的秒数
			  const MillisecondsADay = 24 * 60 * 60 * 1000
			  //  今日零点时间戳
			  const timestamp = Math.floor(new Date(new Date().setHours(0, 0, 0, 0)).getTime())
			  const weekDay = new Date().getDay() === 0 ? (7 - 1) : (new Date().getDay() - 1)
			  const weekTimeStamp = timestamp - MillisecondsADay * weekDay //本周开始时间戳
			  let weekIncomeCount = await db
			    .collection('platform_bill')
			    .aggregate().match({
			  				'create_date.time_stamp': db.command.gt(weekTimeStamp)
			  			  })
			    .group({
			      _id: null,
			      totalPrice: $.sum('$price')
			    })
			    .end()
				
				if(weekIncomeCount.affectedDocs==1){
					var weekIncomeCountPrice = weekIncomeCount.data[0].totalPrice;
				}else{
					var weekIncomeCountPrice = 0;
				}
				
				  date.setDate(1)
				  date.setHours(0, 0, 0, 0)
				  const monthTimeStamp = date.getTime();//本月开始时间戳
				  let monthIncomeCount = await db
				    .collection('platform_bill')
				    .aggregate().match({
				  				'create_date.time_stamp': db.command.gt(monthTimeStamp)
				  			  })
				    .group({
				      _id: null,
				      totalPrice: $.sum('$price')
				    })
				    .end()
					
					if(monthIncomeCount.affectedDocs==1){
						var monthIncomeCountPrice = monthIncomeCount.data[0].totalPrice;
					}else{
						var monthIncomeCountPrice = 0;
					}
					
					
		  return {
			  incomeCount:parseFloat(incomeCountPrice/100).toFixed(2),//平台总收入
			  todayIncomeCount:parseFloat(todayIncomeCountPrice/100).toFixed(2),//今天总收入
			  weekIncomeCount:parseFloat(weekIncomeCountPrice/100).toFixed(2),//本周收入
			  monthIncomeCount:parseFloat(monthIncomeCountPrice/100).toFixed(2) //本月收入
		  };
	},
	//用户充值
	async checkRecharge(data){
		var db = uniCloud.database();
		//判断当前订单是否已经支付过
		var orderData = await db.collection('recharge_log').where({order_no:data.order_no}).get({getOne:true});
		var order = orderData.data[0];
		if(order && order._id){
			return '该订单已经支付过，请勿重复支付'
		}else{
			return db.collection('recharge_log').add(data);
		}
	},
	//增加用户金额
	async setUsersMoney(order_no,total_fee){
		var db = uniCloud.database();
		var cmd = db.command;
		//根据订单号查询出用户id
		var orderData = await db.collection('recharge_log').where({order_no:order_no}).get({getOne:true});
		var order = orderData.data[0];
		return await db.collection('uni-id-users').where({_id:order.user_id}).update({
			money:cmd.inc(total_fee)
		});
	},
	//用户余额支付时减去用户表的金额
	async setUserMoneyDec(userId,money,orderNo){
		var db = uniCloud.database();
		var cmd = db.command;
		var updateData = await db.collection('uni-id-users').where({_id:userId}).update({
			money:cmd.inc(-money)
		});
		
		if(updateData.updated==1){
			//根据订单号查询出对应的订单信息
			 var db = uniCloud.database();
			var result = await db.collection('orders').where({order_no:orderNo}).get({getOne:true});
			//判断支付金额与实际金额是否一致
			var order = result.data[0];
							//更新数据库的支付结果
							var updateData = {
								pay_status:1,//更新成已支付
								user_order_success:true,
								pay_date:new Date().getTime(),
								'status.value':2,
								'status.text':'已接单',
								provider:{
									text:'余额支付',
									value:'yue'
								}
							}
							
							
						var updateResult = await db.collection('orders').where({order_no:orderNo}).update(updateData);
						var orderStatus = {
								text:'已接单',
								value:2,
								create_time:new Date().getTime()
							};
						var orderPayStatus = await db.collection('order_status').where({order_no:orderNo}).update({
							order_status:db.command.push(orderStatus)
						});
						
						return orderPayStatus;
		}
	},
	// 根据用户Id 自增金额（money）
	async updateUsersMoney(Id,money){
		if(!Id){
			return {messsage:'参数不完整',error: '请联系管理员',code: 400}
		}
		const db = uniCloud.database();
		return db.collection('uni-id-users').where({
			_id: Id
		}).update({
			money: db.command.inc(money)
		});
	},
	/**
	 * 插入用户账单表 - (app-web 适用) - 
	 * @param {string} orderNo 订单号
	 * @returns {object} 返回值对象类型 code：200为正确调用
	 */
	async insertUserBill(orderNo) {
		// 参数校验
		if (!orderNo) {
			return {
				messsage:'参数不完整',error: '请联系管理员',code: 400
			};
		}
		const dbjql = uniCloud.databaseForJQL()
		const db = uniCloud.database()
		const clientInfo = this.getClientInfo()
		try {
			// 查询订单信息
			let orderFiled = "address,status,refund,create_date,rider,total_fee,provider,order_no,shop_id"
			let shopFiled = "title,logo,region,_id"
			let order = dbjql.collection("orders").where({order_no:orderNo }).field(orderFiled).getTemp({getOne:true})
			let shop = dbjql.collection("shop").field(shopFiled).getTemp({getOne:true})
			
			let orderRes = await dbjql.collection(order,shop).get({getOne:true,customUI:true})
			orderRes = orderRes.data
			const shopData = orderRes.shop_id[0]
			let result = {
				type:1,
				price:orderRes.total_fee,
				create_date:Date.now(),
				text:"余额支付退款",
				user:orderRes.address.user_id,
				shop:{
					_id:shopData._id,
					title:shopData._id,
					logo:shopData.logo.path
				},
				side_user:{
					_id:orderRes.address.user_id,
					nickname:orderRes.address.name,
					avatar:orderRes.address.avatar,
				},
				order_no:orderRes.order_no,
				create_ip: clientInfo.clientIP
			}
			const addRes = await dbjql.collection("users_bill").add(result)
			return {
				code: 200,
				message: '成功',
				result:addRes,
			}
			
			
		} catch (error) {
			return {
				message: '内部错误',code: 500,error:'建议先联系相关管理员'+error,
			};
			dbJQL.collection('users_log').add({type: 2,text: `店铺${Data.shop_id},在‘获取可提现金额’方法时发生错误：${err}`})
		}
	},
	
	
}
